/**
 * 游戏列表菜单的管理
 */
// 填充系统菜单
var drawGameList = function() {
    $(".gamelist .game").remove();
    var f = function(key, name, c) {
        var l = '<li value="__k__" class="game"><a href="#" class="__k__">__name__</a></li>';
        l = l.replace(/__k__/g, key);
        l = l.replace(/__name__/g, name);
        if (!c) {
            $(".gamelist .am-parent").before(l);
        }
        else
            c.append(l);
    }
    var curr = urlInfo.params.game || 'bjpk10';
    var list = get_game_lists();
    for (var i = 0; i < 8; i++) {
        if (!list[i]) continue;
        if (list[i].game == curr) continue;
        if (urlInfo.params.wx == 1 && list[i].game.startsWith("zy")) continue;
        f(list[i].game, get_game_display_name(list[i].game));
    }
    for (var i = 8; i < list.length; i++) {
        if (!list[i]) continue;
        if (list[i].game == curr) continue;
        if (urlInfo.params.wx == 1 && list[i].game.startsWith("zy")) continue;
        f(list[i].game, get_game_display_name(list[i].game), $(".gamelist .more"));
    }

    var cb = function(e) {
        var target = $(e.currentTarget);
        var game = target.attr("value");
        if (game == curr) return;
        if (game == 'system' || game == 'am-parent') return;

        // 切换游戏
        Util.jumpUrl({
            game: game
        });
    };
    var arr = $(".gamelist li.game");
    for (var i = 0; i < arr.length; i++) {
        $(arr[i]).click(cb);
    }
    $("li.gamehall").click(function() {
        Util.jumpUrl({
            file: 'center.html',
            cmd: 'gamecenter',
        });
    });
};

// 取得我的菜单配置信息
var menuOrders = {};
function get_game_lists() {
    var games = get_game_list();
    var r = [];
    for (var i in games) {
        var game = games[i];
        if (menuOrders[game] === undefined) continue;
        r.push({
            game: game,
            order: parseInt(i),
        });
    }
    r.sort(function(a, b) {
        var aorder = a.order, border = b.order;
        if (menuOrders[a.game] !== undefined) aorder = parseInt(menuOrders[a.game]);
        if (menuOrders[b.game] !== undefined) border = parseInt(menuOrders[b.game]);
        return aorder - border;
    });
    return r;
}

$(function() {
    drawGameList();

    // 游戏名称
    var curr = urlInfo.params.game || 'bjpk10';
    $(".game-title span").html(get_game_display_name(curr));
    $("title").html(get_game_display_name(curr));
});

// 拉取服务器的游戏顺序配置
Classify.queryExt("games", "order", true, {}, function(r) {
    menuOrders = {};
    for (var i in r) {
        if (r[i] == -1) continue;
        menuOrders[i] = r[i];
    }
    drawGameList();
});
